<template>
  <div ref="chartDom" class="bar-chart"></div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Array,
    required: true
  }
});

const chartDom = ref(null);
let myChart = null;

const initChart = () => {
  if (!props.chartData.length) return;
  
  // 如果图表已存在，先销毁
  if (myChart) {
    myChart.dispose();
  }
  
  myChart = echarts.init(chartDom.value);

  // 柱状图配置
  const option = {
    title: {
      text: '图书类型分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}本'
    },
    xAxis: {
      type: 'category',
      data: props.chartData.map(item => item.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '数量(本)',
      nameLocation: 'middle',
      nameGap: 25
    },
    series: [
      {
        name: '图书数量',
        type: 'bar',
        barWidth: '60%',
        data: props.chartData.map(item => item.value),
        itemStyle: {
          color: function (params) {
            const colorList = ['#5470C6', '#91CC75', '#FAC858', '#EE6666'];
            return colorList[params.dataIndex % colorList.length];
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}本'
        }
      }
    ]
  };

  myChart.setOption(option);

  window.addEventListener('resize', function () {
    myChart.resize();
  });
};

onMounted(() => {
  initChart();
});

// 监听数据变化
watch(() => props.chartData, () => {
  initChart();
}, { deep: true });
</script>

<style scoped>
.bar-chart {
  width: 100%;
  height: 400px;
  min-width: 300px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>